import React, { useEffect, useState } from "react";
import '../../appcommon.css';
import styles from './transfer.module.css';
import { useDispatch } from "react-redux";
import { Dialog, DotLoading, Mask, Toast } from "antd-mobile";
import { saveEvent } from "@/store/actions/saveEvent";
import { useHistory } from "react-router-dom/cjs/react-router-dom.min";
import icon_transfer_contact from '@/assets/icon_transfer_contact.png'

import NavigateBar from "@/components/NavigateBar";
import TransferInput from "@/components/TransferInput/transferInput";
import { withdrawCreate, withdrawGetBalance } from "@/store/actions/user";
import { getTransferInfo, setTransferResultInfo } from "@/utils/storage";
import TransferPwdInput from "@/components/TransferInput/transferPwdInput";
import { LangEn } from "@/utils/langEn";

/**
 * 登录页
 */
export default function Transfer() {

    //loading状态
    const [maskVisible, setMaskVisible] = useState(false)

    //显示add home弹框
    const [addHomeMaskVisible, setAddHomeMaskVisible] = useState(false);
    const [addHomeMaskIsHomeMode, setAddHomeMaskIsHomeMode] = useState(true);

    // 当前 币
    const [curCoinType, setCurCoinType] = useState("")

    // 当前 账号
    const [curAddress, setCurAddress] = useState("")

    // 当前 金额
    const [curAmount, setCurAmount] = useState("")

    // 当前 金币种额
    const [curCoin, setCurCoin] = useState({})

    // 文案翻译
    const [curLang, setCurLang] = useState(LangEn);

    // 获取 Redux 分发器
    const dispatch = useDispatch()

    //router
    const history = useHistory()

    // 当前输入内容
    let curInputPassword = "";

    //清空登录信息
    useEffect(() => {
        //关闭loading
        setMaskVisible(false);

        // 清空缓存
        setTransferResultInfo(null);

        // 获取币种信息
        const coinInfo = getTransferInfo();
        const coninType = coinInfo.coinType || "";
        setCurCoinType(coninType);
        doWithdrawGetBalance(coninType);

        //打点
        doHitEvent("TRANSFER_START")

        return () => {
            //打点
            doHitEvent("TRANSFER_END")
        }
    }, [])

    // 点击下一步
    const onHandleSubmit = () => {

        console.log('curAddress:' + curAddress)
        console.log('curAmount:' + curAmount)
        console.log('balance:' + curCoin.balance)

        if (curAddress.length <= 0) {
            Toast.show(curLang.transferTheTransferAddressCannotBeNull);
            return;
        }

        let amountF = parseFloat(curAmount);
        if (!amountF || amountF <= 0) {
            Toast.show(curLang.transferTheTransferAmountCannotBe0);
            return;
        }

        if (curCoin.balance <= 0) {
            Toast.show(curLang.transferTheBalanceIs0);
            return;
        }

        // 显示交易密码框
        Dialog.alert({
            title: curLang.transferEnterPassword,
            content: <TransferPwdInput onInputChanged={(text) => {
                onHandleDialogInputChanged(text);
            }} />,
            confirmText: curLang.transferTransfer,
            onConfirm: () => {
                console.log("点击了确认：" + curInputPassword);
                // 发起提币
                doWithdrawCreate();
            }
        });
    };

    const onHandleDialogInputChanged = (text) => {
        curInputPassword = text;
    };


    // 获取余额 返回
    const onDoWithdrawGetBalanceCallback = (success, data) => {
        //关闭loading
        setMaskVisible(false)
        console.log('获取余额 返回: ' + success);

        if (success && data) {
            // 处理流程业务
            // {
            //     "address": "132A3kUhBh9jGHM6m9YAvwZULi5NXZg6cR",
            //     "balance": 0,
            //     "unit": "BTC"
            // }

            let address = data.address || "";
            if (address.length <= 0) {
                data.address = address;
            }

            // 测试
            // data.balance = 1000;

            // 保存
            setCurCoin(data);
        }
    };

    // 发起提币 返回
    const onDoWithdrawCreateCallback = (success, data) => {
        //关闭loading
        setMaskVisible(false)
        console.log('获取余额 返回: ' + success);

        if (success && data) {
            // 处理流程业务
            // {
            //     "address": "132A3kUhBh9jGHM6m9YAvwZULi5NXZg6cR",
            //     "balance": 0,
            //     "unit": "BTC"
            // }

            const date = new Date();
            let year = date.getFullYear();
            let month = date.getMonth() + 1;
            if (month < 10) {
                month = "0" + month;
            } else {
                month = "" + month;
            }

            let day = date.getDate();
            if (day < 10) {
                day = "0" + day;
            } else {
                day = "" + day;
            }
            let dateFormat = day + "/" + month + "/" + year;

            // 跳转 结果页
            let resultInfo = {
                coinType: curCoinType,
                amount: curAmount,
                address: curAddress,
                unit: curCoin.unit,
                date: dateFormat
            }

            // 保存缓存
            setTransferResultInfo(resultInfo);

            // 清空
            setCurAmount("");

            // 跳转
            history.push('/transferresult');
        }
    };

    //打点接口
    const doHitEvent = async (type, remark = "") => {
        console.log("doHitEvent: " + type + " , " + remark);

        try {
            //获取Action
            const action = saveEvent(type, remark)

            //触发接口
            await dispatch(action)

        } catch (e) {
            console.log(e)
        }
    }

    // 获取余额
    const doWithdrawGetBalance = async (coinType) => {
        console.log("doWithdrawGetBalance: ");

        try {
            //显示loading
            setMaskVisible(true)

            //获取Action
            const action = withdrawGetBalance(coinType, onDoWithdrawGetBalanceCallback)

            //触发接口
            await dispatch(action)

        } catch (e) {
            console.log(e)
        }
    }

    // 发起提币
    const doWithdrawCreate = async () => {
        console.log("doWithdrawCreate: ");

        if (curAddress.length <= 0) {
            Toast.show(curLang.transferTheTransferAddressCannotBeNull);
            return;
        }

        if (curAmount.length <= 0) {
            let amountF = parseFloat(curAmount);
            if (amountF <= 0) {
                Toast.show(curLang.transferTheTransferAmountCannotBe0);
                return;
            }
            return;
        }

        if (curCoinType.length <= 0) {
            Toast.show(curLang.withdrawTheCoinTypeCanNotBeNull);
            return;
        }


        if (curInputPassword.length < 6) {
            Toast.show(curLang.transferThePasswordCannotBeNull);
            return;
        }

        // 测试
        // if (false) {
        //     const date = new Date();
        //     let year = date.getFullYear();
        //     let month = date.getMonth() + 1;
        //     if (month < 10) {
        //         month = "0" + month;
        //     } else {
        //         month = "" + month;
        //     }

        //     let day = date.getDate();
        //     if (day < 10) {
        //         day = "0" + day;
        //     } else {
        //         day = "" + day;
        //     }
        //     let dateFormat = day + "/" + month + "/" + year;

        //     // 跳转 结果页
        //     let resultInfo = {
        //         coinType: curCoinType,
        //         amount: curAmount,
        //         address: curAddress,
        //         unit: curCoin.unit,
        //         date: dateFormat
        //     }

        //     // 保存缓存
        //     setTransferResultInfo(resultInfo);

        //     // 清空
        //     setCurAmount("");

        //     // 跳转
        //     history.push('/transferresult');
        //     return;
        // }

        try {
            //显示loading
            setMaskVisible(true)

            //获取Action
            const action = withdrawCreate(curCoinType, curAddress, curAmount, onDoWithdrawCreateCallback)

            //触发接口
            await dispatch(action)

        } catch (e) {
            console.log(e)
        }
    }



    return (
        <div className='pageRoot pageBackgroundColorGray'>
            <NavigateBar theme="white" showLogout={false} onAddFavorite={() => { setAddHomeMaskIsHomeMode(false); setAddHomeMaskVisible(true) }} onAddHome={() => { setAddHomeMaskIsHomeMode(true); setAddHomeMaskVisible(true) }}>{curLang.transferTransfer}</NavigateBar>

            {/* 使用添加 home screen bar */}
            {/* <AddFavorite onAddHome={() => { setAddHomeMaskIsHomeMode(true); setAddHomeMaskVisible(true) }} /> */}

            <div className="pageContentColumnFullPaddingHorizontal16px">
                {/* To */}
                <div className={styles.transferTitle}>To</div>

                <div className={styles.transferTextRow}>
                    <TransferInput
                        value={curAddress}
                        onChange={e => { setCurAddress(e.target.value) }}
                        extIcon={icon_transfer_contact}
                        placeholder={curLang.transferTransferAddress}
                        type="text"
                        autoComplete="off" />
                </div>

                <div className={styles.transferAmountRow}>
                    <div className={styles.transferAmountTitle}>{curLang.transferAmount}</div>
                    <div className={styles.transferAmountValue}>{curCoin.balance} {curCoin.unit}</div>
                </div>

                <div className={styles.transferTextRow}>
                    <TransferInput
                        value={curAmount}
                        onChange={e => { setCurAmount(e.target.value) }}
                        placeholder="0"
                        type="number"
                        autoComplete="off" />

                    <div className={styles.transferAmountLine}></div>
                    <div className={styles.transferMemo}>{curLang.transferMemoNeed1TRX}</div>
                </div>


                {/* 提交 */}
                <div className="pageBtnSubmit pageMarginTop16px" onClick={onHandleSubmit}>{curLang.transferNext}</div>
            </div>

            {/* 底部 margin */}
            <div className="pageBottomEdge"></div>

            {/* load mask */}
            <Mask visible={maskVisible} opacity={0.1}
                onMaskClick={() => { }}>
                <div className="pageLoadingOverlayContent">
                    <span style={{ fontSize: 24, color: '#3498DB' }} >
                        <DotLoading color="currentColor" />
                    </span>
                </div>
            </Mask>
        </div >
    )
}